package org.sjs.dreamfly.biz.movie

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.core.widget.doAfterTextChanged
import androidx.fragment.app.DialogFragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.google.common.eventbus.Subscribe
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import org.sjs.dreamfly.R
import org.sjs.dreamfly.app.SearchListLoadedEvent
import org.sjs.dreamfly.app.defaultEventBus
import org.sjs.dreamfly.browser.BrowserConst
import org.sjs.dreamfly.model.MovieInfo
import org.sjs.dreamfly.common.util.LogUtil
import org.sjs.dreamfly.common.util.Router
import org.sjs.dreamfly.browser.PhemonWebView
import org.sjs.dreamfly.data.Config

class MovieSearchDialog: DialogFragment() {

    private var keywords: String? = null
    private val mainScope by lazy { MainScope() }
    private val movieList = mutableListOf<MovieInfo>()
    private lateinit var btnBack: View
    private lateinit var searchView: EditText
    private lateinit var btnSearch: View
    private lateinit var loadingView: View
    private lateinit var recyclerView: RecyclerView
    private lateinit var webView: PhemonWebView

    override fun onStart() {
        super.onStart()
        defaultEventBus.register(this)
        dialog?.window?.let {
            val layoutParams: WindowManager.LayoutParams = it.attributes
            layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT
            layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT
            it.attributes = layoutParams
            it.setBackgroundDrawableResource(R.color.white)
        }
    }

    override fun onStop() {
        super.onStop()
        defaultEventBus.unregister(this)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.dialog_movie_search, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        findViews(view)
        initViews()
    }

    @SuppressLint("NotifyDataSetChanged")
    @Subscribe()
    private fun onEventSearchListLoaded(event: SearchListLoadedEvent) {
        LogUtil.d("event:${event.movieList}")
        mainScope.launch {
            loadingView.visibility = View.GONE
            event.movieList.forEach { it.name = keywords }
            movieList.addAll(event.movieList)
            recyclerView.adapter?.notifyDataSetChanged()
        }
    }

    private fun findViews(view: View) {
        btnBack = view.findViewById(R.id.btn_back)
        searchView = view.findViewById(R.id.edit_keywords)
        btnSearch = view.findViewById(R.id.btn_search)
        loadingView = view.findViewById(R.id.loading_view)
        recyclerView = view.findViewById(R.id.recycler_view)
        webView = view.findViewById(R.id.web_view)
    }

    private fun initViews() {
        btnBack.setOnClickListener { dismissAllowingStateLoss() }
        btnSearch.setOnClickListener { search() }
        searchView.doAfterTextChanged {
            it?.let {
                btnSearch.isEnabled = it.isNotEmpty()
                btnSearch.alpha = if (it.isNotEmpty()) 1.0f else 0.8f
            }
        }
        recyclerView.adapter = object : RecyclerView.Adapter<SearchResultItemViewHolder>() {
            override fun onCreateViewHolder(
                parent: ViewGroup,
                viewType: Int
            ): SearchResultItemViewHolder {
                return SearchResultItemViewHolder(LayoutInflater.from(context).inflate(R.layout.view_holder_movie_search_list, null))
            }
            override fun getItemCount(): Int { return movieList.size }
            override fun onBindViewHolder(holder: SearchResultItemViewHolder, position: Int) {
                holder.bind(movieList[position], position)
            }
        }
        recyclerView.layoutManager = LinearLayoutManager(context)
    }

    private fun search() {
        keywords = searchView.text.toString()
        loadingView.visibility = View.VISIBLE
        val url = "https://www.chihuayu.com/sosoch/----------%3C%3E.html?wd=${keywords}&submit="
        webView.inject(url, BrowserConst.InjectMethod.METHOD_SEARCH_LIST, BrowserConst.InjectPoint.POINT_ON_PROGRESS_MORE_THAN_1)
    }
}

class SearchResultItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    @SuppressLint("SetTextI18n")
    fun bind(movieInfo: MovieInfo, position: Int) {
        val coverView = itemView.findViewById<ImageView>(R.id.movie_cover)
        val titleView = itemView.findViewById<TextView>(R.id.movie_name)
        val scoreView = itemView.findViewById<TextView>(R.id.movie_score)
        val regionView = itemView.findViewById<TextView>(R.id.movie_region)
        val languageView = itemView.findViewById<TextView>(R.id.movie_language)
        val actorsView = itemView.findViewById<TextView>(R.id.movie_actors)
        val directorView = itemView.findViewById<TextView>(R.id.movie_director)

        titleView.text = "${movieInfo.name} (${position+1})"
        Glide.with(itemView.context)
            .load(movieInfo.imageUrl)
            .into(coverView)
        itemView.setOnClickListener {
            Router.launchMovieDetail(movieInfo, MovieConstants.CHANNEL_TYPE_OTHER_CHIHUAYU)
        }
    }
}
